﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fcdbas.Biz;
using Fcdbas.Core;
using Fcdbas.Core.Reflection;
using System.Reflection;
using Fcdbas.WinUI.Forms;
using Fcdbas.WinUI.Common;
using Fcdbas.Core.Xml;

namespace Fcdbas.WinUI.Forms
{
    /// <summary>
    /// 表现层实现
    /// </summary>
    internal class MainFormPresenter
    {
        private IMainFormView mainFormView;
        private static List<fnd_exp_navigator> navList;
        private static Dictionary<String, AssemblyX> AssemblyXList = new Dictionary<string, AssemblyX>();
        private string AssemblyPath = AppDomain.CurrentDomain.BaseDirectory;
        private List<RecentModule> recentList;
        public List<string> FavList;
        public fnd_user_profile FavModule;
        public fnd_user_profile RecentModule;
        public fnd_user_profile UserSkin;
        public readonly string NVA_TYPE_PARENT = "Parent";
        public MainFormPresenter(IMainFormView view)
        {
            mainFormView = view;
            Init();   
        }
        public void Init()
        {
            FavList = new List<string>();
            recentList = new List<Biz.RecentModule>();
            RecentModule = FndDAL.FindUserProfile(AppEnvironment.Session.USER_ID, "MainForm", "U");
            if (RecentModule == null)
            {
                RecentModule = new fnd_user_profile();
                RecentModule.identity = AppEnvironment.Session.USER_ID;
                RecentModule.pres_object = "MainForm";
                RecentModule.type_flag = "U";
                RecentModule.description = "最近打开的项目";
                recentList = new List<RecentModule>();
                RecentModule.Status = RecordStatus.New;
            }
            else
            {

                if (!string.IsNullOrEmpty(RecentModule.info))
                {
                    recentList = RecentModule.info.ToXmlEntity<List<RecentModule>>();
                }
            }
            FavModule = FndDAL.FindUserProfile(AppEnvironment.Session.USER_ID, "MainForm", "F");
            if (FavModule == null)
            {
                FavModule = new fnd_user_profile();
                FavModule.identity = AppEnvironment.Session.USER_ID;
                FavModule.pres_object = "MainForm";
                FavModule.type_flag = "F";
                FavModule.description = "用户收藏";
                FavList = new List<string>();
                FavModule.Status = RecordStatus.New;
            }
            else
            {

                if (!string.IsNullOrEmpty(FavModule.info))
                {
                    FavList = FavModule.info.ToXmlEntity<List<string>>();
                }
            }

            UserSkin = FndDAL.FindUserProfile(AppEnvironment.Session.USER_ID, "MainForm", "S");
            if (UserSkin == null)
            {
                UserSkin = new fnd_user_profile();
                UserSkin.identity = AppEnvironment.Session.USER_ID;
                UserSkin.pres_object = "MainForm";
                UserSkin.type_flag = "S";
                UserSkin.description = "用户皮肤";
                UserSkin.Status = RecordStatus.New;
                UserSkin.info = "DevExpress Style";
            }
        }
        public bool IsAvaliable(string preObject)
        {
            return Security.IsAuthorize(AppEnvironment.Session.USER_ID, preObject, preObject, SecObjectType.Window);
        }
        public void Reset()
        {
            this.FavList.Clear();
            this.recentList.Clear();
        }
        public void SaveRecentModuleToProfile()
        {
            var nvs = from r in recentList
                      //orderby r.Hint descending
                      orderby r.LastClickTime descending
                      select r;
            List<RecentModule> list = new List<Biz.RecentModule>();
            int nCount = 0;
            foreach (RecentModule rec in nvs)
            {
                list.Add(rec);
                if (nCount > 8)
                    break;
                nCount++;
            }
            RecentModule.info = list.ToXml();
            if (RecentModule.Status != RecordStatus.Normal)
            {
                FndDAL.UserProfileNew(RecentModule);
            }
            else
            {
                FndDAL.UserProfileModify(RecentModule);
            }
        }
        public void SaveFavModuleToProfile()
        {
            FavModule.info = FavList.ToXml();
            if (FavModule.Status != RecordStatus.Normal)
            {
                FndDAL.UserProfileNew(FavModule);
            }
            else
            {
                FndDAL.UserProfileModify(FavModule);
            }
        }
        public void ClickModule(fnd_exp_navigator nav)
        {
            RecentModule rm = recentList.Find(p => p.nav_key == nav.nav_key);
            if (rm != null)
            {
                rm.Hint += 1;
                rm.LastClickTime = DateTime.Now;
            }
            else
            {
                rm = new RecentModule();
                rm.nav_key = nav.nav_key;
                rm.Hint = 1;
                rm.LastClickTime = DateTime.Now;
                recentList.Add(rm);
            }
           // RecentModule.Status = RecordStatus.Edit;
        }
        public static fnd_exp_navigator FindNavigator(string nav_key)
        {
            if (navList == null || navList.Count == 0)
                return null;
            return navList.Find(p => p.nav_key == nav_key);
        }
        public void DisplayRecentModule()
        {
            mainFormView.DisplayRecentModuleView(navList, recentList);
        }

        public void DisplayFavModule()
        {
            mainFormView.DisplayFavModuleView(navList, FavList);
        }
        public void DisplayNavigator()
        {
            if (!Fcdbas.WinUI.Common.Security.IsViewAvaliable(Fcdbas.WinUI.Common.AppEnvironment.Session.USER_ID, "fnd_exp_navigator"))
            {
                Fcdbas.WinUI.Common.WinTranslate.GetTranslate().ShowMessage("没有查询视图[%%1]的权限，请联系系统管理员。", "fnd_exp_navigator");
                return ;
            }
            //navList = Entity<fnd_exp_navigator>.FindAll("","ordinal","",0,0);
            if (AppEnvironment.Session.IsRoot)
                navList = Entity<fnd_exp_navigator>.FindAll("actived='True'", "ordinal", "", 0, 0);
            else
            {
                List<fnd_exp_navigator> list = Entity<fnd_exp_navigator>.FindAll("actived='True'", "ordinal", "", 0, 0);
                var parents = from nav in list
                              where nav.key_type == NVA_TYPE_PARENT && string.IsNullOrEmpty(nav.parent_key)
                              select nav;

                var list2 = UserSecurity.UserSecs.GroupBy(p => p.pres_object).ToList();
                
                var list3 = (from nav in list
                          from sec in list2
                          where nav.pres_object == sec.Key
                          select nav).ToList();
                var parentKeys = list3.GroupBy(p => p.parent_key).ToList();
                var hasparents = (from p in parents
                                  from c in parentKeys
                                 where p.nav_key == c.Key
                                      select p).ToList();
                navList = hasparents.Concat(list3).ToList();
            }
            mainFormView.DisplayNavigatorView(navList);
        }
        public BaseForm LoadForm(string assembly,string FormType)
        {

            object obj = CreateObject(assembly, FormType);
            return obj as BaseForm;
        }
        public object CreateObject(string assembly, string FormType)
        {
            string asmFile = AssemblyPath + assembly;
            if (!System.IO.File.Exists(asmFile))
            {
                this.mainFormView.ShowMessage("模块[%%1]不存在", asmFile);
                return null;
            }
            AssemblyX asmx;
            if (AssemblyXList.ContainsKey(asmFile))
                asmx = AssemblyXList[asmFile];
            else
            {
                var asm2 = Assembly.LoadFile(asmFile);
                asmx = AssemblyX.Create(asm2);
                AssemblyXList.Add(asmFile, asmx);
            }
            Type t = asmx.GetType(FormType);

            if (t == null)
            {
                this.mainFormView.ShowMessage("模块%1不存在", asmFile);
                return null;
            }
            return TypeX.CreateInstance(t);
        }
        /// <summary>
        /// 打开模块
        /// </summary>
        /// <param name="nav"></param>
        /// <returns></returns>
        public BaseForm OpenModule(fnd_exp_navigator nav)
        {
            return LoadForm(nav.assembly_dll, nav.pres_object);
            //string asmFile = AssemblyPath + nav.assembly_dll;
            //if (!System.IO.File.Exists(asmFile))
            //{
            //    this.mainFormView.ShowMessage("模块[%%1]不存在", asmFile);
            //    return null;
            //}
            //AssemblyX asmx;
            //if (AssemblyXList.ContainsKey(asmFile))
            //    asmx = AssemblyXList[asmFile];
            //else
            //{
            //    var asm2 = Assembly.LoadFile(asmFile);
            //    asmx = AssemblyX.Create(asm2);
            //    AssemblyXList.Add(asmFile, asmx);
            //}
            //Type t = asmx.GetType(nav.pres_object);

            //if (t == null)
            //{
            //    this.mainFormView.ShowMessage("模块%1不存在", asmFile);
            //    return null;
            //}
            //object obj = TypeX.CreateInstance(t);
            //return obj as BaseForm;
        }
    }
}
